/*seserver base.js
 */
function OnLoad() {
    view = $('#level_view')[0];
    bar = $('#scroll_bar')[0];
    page = $('html')[0];
    bar_length = view.width; 
    bar_location = 0;
    points = [];
    level = [];
    view.currentX = 0;
    view.maxX = 0;
    current_mouse_x = 0;
    current_mouse_y = 0;
    view_drag_bool = false;
    view_did_drag_bool = false;
    was_dragging = false;
    bar_drag_bool = false;
    point_move_bool = false;
    delete_point_bool = false;
    context = view.getContext('2d');
    bar_context = bar.getContext('2d');
    page.onmousemove = mouse_move;
    page.onmouseup = end_drag;
    view.onmousedown = view_mouse_down;
    view.onclick = view_click;
    bar.onmousedown = bar_drag;
    original_onselectstart = document.onselectstart;
    selected_point = '';
    points = [];
    visible_points = [];
    hovering = false;
}

function mouse_move(e){
    if ((!view_drag_bool) && (!bar_drag_bool) && (!point_move_bool)
        && (e.srcElement.id=='level_view')){
        hovering = false;
        temp_mouse_x = view.currentX + e.offsetX;
        temp_mouse_y = view.height - e.offsetY;
        for(var i = 0;i < visible_points.length;i++){
            var x = visible_points[i].x;
            var y = visible_points[i].y;
            if((temp_mouse_x > (x - 3)) && (temp_mouse_x < (x + 6))){
                if((temp_mouse_y > (y - 6)) && (temp_mouse_y < (y + 3))){
                    if(delete_point_bool){
                        view.style.cursor = "url('/seserver/static/images/eraser.png')";
                    }
                    else{
                        view.style.cursor = 'move';
                    }
                    hovering = true;
                    current_point = visible_points[i]
                }
                
            }
        }
        if(!hovering){
           view.style.cursor = 'default';
        }
    }
    var old_mouse_x = current_mouse_x;
    current_mouse_x = e.pageX;
    var old_mouse_y = current_mouse_y;
    current_mouse_y = e.pageY;
    deltaX = old_mouse_x - current_mouse_x;
    deltaY = old_mouse_y - current_mouse_y;
    if(view_drag_bool){
        view.currentX += deltaX; 
        view_did_drag_bool = true;
    }
    else if(bar_drag_bool){
        view.currentX -= deltaX*(view.maxX+view.width)/view.width;
    }
    else if(point_move_bool){
        current_point.x -= deltaX;
        current_point.y += deltaY;
        if(current_point.y > view.height-10){
            current_point.y = view.height - 10;
        }
        
    }
    if(view.currentX < 0)
        view.currentX = 0;
    if(view.currentX > view.maxX)
        view.currentX = view.maxX;
    refresh_view();
}

function view_mouse_down(e){
    if(hovering && !delete_point_bool){
        point_move_bool = true;
        }
    else if(hovering && delete_point_bool){
        for(var i = 0; i < points.length; i++){
            if (current_point == points[i]){
                points.splice(i, 1);
            }
        }
    }
    else {
        view_drag_bool = true;
        document.onselectstart = function(){return false;}
    }
    was_dragging = false;
    refresh_view();
}

function view_click(e){
    if(new_point_bool && !was_dragging){
        var new_point = {'level_id':level.id, 'x':e.offsetX +
            view.currentX, 'y':view.height - e.offsetY}
        if(new_point.y > view.height - 10){
           new_point.y = view.height - 10; 
        }
        points[points.length] = new_point;
        refresh_view();
    }
    was_dragging = false;
}

function bar_drag(e){
    bar_drag_bool = true;
    bar_jump(e);
    document.onselectstart = function(){return false;}
}

function end_drag(e){
    if(point_move_bool || view_did_drag_bool || bar_drag_bool){
        was_dragging = true;
    }
    view_drag_bool = false;
    view_did_drag_bool = false;
    bar_drag_bool = false;
    point_move_bool = false;
    document.onselectstart = original_onselectstart;
}


function refresh_view(){
    var last = 0;
    for(var i = 0; i < points.length; i++){
        if(points[i].x > last){
            last = points[i].x;
        }
    }
    view.maxX = last - view.width/3;
    if(view.maxX < view.width){
        view.maxX = view.width * 1.5;
    }
    visible_points = new Array();
    for(var i = 0; i < points.length; i++){
        if((points[i].x <= (view.currentX+view.width)) && (points[i].x >= view.currentX)){
            visible_points[visible_points.length] = points[i];
        }
    }
    bar_length = view.width * view.width/view.maxX;
    bar_location = view.currentX/view.maxX*(view.width-bar_length);

    redraw_canvas();
}
function bar_jump(e){
    view.currentX = (e.offsetX/view.width)*(view.maxX+view.width) - (view.width/2);
    if(view.currentX < 0)
        view.currentX = 0;
    if(view.currentX > view.maxX)
        view.currentX = view.maxX;
    refresh_view();
}

function redraw_canvas(){
    context.clearRect(0, 0, view.width, view.height);
    for(var i = 0; i < visible_points.length; i++){
        context.fillRect(visible_points[i].x-view.currentX,
            view.height - visible_points[i].y, 3, 3);
    }
    bar_context.clearRect(0, 0, bar.width, bar.height);
    bar_context.fillRect(bar_location, 0, bar_length, bar.height);
}

function load_level(id){
    $('#result').html('');
    $('.level_button').each(
        function(ind, elem){
            elem_deselect(elem);
            });
    elem_select($('#'+id)[0]);
    if(id==="new"){
        points = [];
        level = {};
        level.id = 'new';
        clear_inputs();
        return;
    }
    $.ajax({
        url: '/seserver/weblevel/'+id,
        headers: {
            'Accept': 'application/json'
        },
        type: 'GET',
        beforesend: function(){
                            
        },
        success: function(jqXHR, textStatus){
            points = jqXHR.data.level[0].points;
            level = jqXHR.data.level[0];
            $('#display_name').val(level.display_name);
            $('#name').val(level.name);
            $('#hill_color_base').val(level.hill_color_base.hex_str);
            $('#hill_color_base')[0].color.importColor();
            $('#hill_alpha_base').val(level.hill_color_base.a);
            $('#hill_color_alt').val(level.hill_color_alt.hex_str);
            $('#hill_color_alt')[0].color.importColor();
            $('#hill_alpha_alt').val(level.hill_color_alt.a);
            $('#sky_color').val(level.sky_color.hex_str);
            $('#sky_color')[0].color.importColor();
            $('#sky_alpha').val(level.sky_color.a);
            $('#sequence').val(level.sequence);
            $('#active').prop('checked', level.active);
            $('#gravity_factor_x').val(level.gravity_factor_x);
            $('#gravity_factor_y').val(level.gravity_factor_y);
            $('#creator')[0].textContent = level.creator_username;
            $('#time_to_complete').val(level.time_to_complete);
            refresh_view();
        },
        error: function(jqXHR, textStatus, errorThrown){
        }   
    });        

}

function elem_select(elem){
    elem.style.background = 'grey';
    elem.style.color = 'white';
}
function elem_deselect(elem){
    elem.style.background = 'silver';
    elem.style.color = '#444444';
}

new_point_bool = false;
prev_cursor = '';
function toggle_new_point(){
    elem_deselect($('#delete_point_button')[0]);
    delete_point_bool = false;
    if(new_point_bool == true){
        new_point_bool = false;
        elem_deselect($('#new_point_button')[0]);
        view.style.cursor = prev_cursor;
    }
    else{
        new_point_bool = true;
        prev_cursor = view.style.cursor;
        elem_select($('#new_point_button')[0]);
        view.style.cursor = 'crosshair';
    }

}
function toggle_delete_point(){
    elem_deselect($('#new_point_button')[0]);
    new_point_bool = false;
    if(delete_point_bool){
        delete_point_bool = false;
        elem_deselect($('#delete_point_button')[0]);
    }
    else {
        delete_point_bool = true;
        elem_select($('#delete_point_button')[0]);
    }
}

function clear_inputs(){
    $('input').each(function(ind, elem){
        if(elem.type !== 'button'){
            elem.value = '';
        }
    });
    color_inputs = $('.color');
    color_inputs.val('#FFFFFF');
    color_inputs.each(function(ind, elem){elem.color.importColor();});
    $('#creator')[0].textContent = username;
    $('#active').prop('checked', false);
}

function clone_level(){
    level.id = 'new';
    $('#creator')[0].textContent = username;
    $('#display_name').val('');
    $('#name').val('');
    $('#active').prop('checked', false);
}

function send_level(){
    $('#result').html('');
    if(level.id === 'new'){
        var method = 'POST';
        var url = '/seserver/weblevel/';
    }
    else{
        var method = 'PUT';
        var url = '/seserver/weblevel/'+level.id;
    }
    data = {}
    data['display_name'] = $('#display_name').val();
    data['name'] = $('#name').val();
    data['hill_color_base'] = $('#hill_color_base').val();
    data['hill_alpha_base'] = $('#hill_alpha_base').val();
    data['hill_color_alt'] = $('#hill_color_alt').val();
    data['hill_alpha_alt'] = $('#hill_alpha_alt').val();
    data['sky_color'] = $('#sky_color').val();
    data['sky_alhpa'] = $('#sky_alpha').val();
    data['sequence'] = $('#sequence').val();
    data['active'] = $('#active').prop('checked');
    data['gravity_factor_x'] = $('#gravity_factor_x').val();
    data['gravity_factor_y'] = $('#gravity_factor_y').val();
    data['time_to_complete'] = $('#time_to_complete').val();
    data['points'] = JSON.stringify(points);
    
    $.ajax({
        url: url,
        headers: {
            'Accept': 'application/json'
        },
        type: method,
        data: data,
        beforesend: function(){
                            
        },
        success: function(jqXHR, textStatus){
            window.location.reload();
        },
        error: function(jqXHR, textStatus, errorThrown){
            result = JSON.parse(jqXHR.responseText);
            $('#result').html(result.errors[0]);
        }   
    });        

}
function reload_level(){
    load_level(level.id);
}
function clear_points(){
    points.splice(0,points.length);
    refresh_view();
}
